package com.mingtang.online.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.mingtang.online.R;
import com.mingtang.online.activity.ShopDetailActivity;
import com.mingtang.online.adapter.NormalRecyclerAdapter;
import com.mingtang.online.bean.Person;
import com.mingtang.online.pulltorefresh.XRefreshView;
import com.mingtang.online.pulltorefresh.utils.LogUtils;
import com.mingtang.online.view.IWebView;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2015/12/11.
 */
public class FanliFragment extends BaseFragment implements XRefreshView.XRefreshViewListener {
    RecyclerView recyclerView;
    NormalRecyclerAdapter adapter;
    List<Person> personList = new ArrayList<Person>();
    XRefreshView xRefreshView;
    int lastVisibleItem = 0;
    //    GridLayoutManager layoutManager;
    LinearLayoutManager layoutManager;
    private boolean isBottom = false;
    private int mLoadCount = 0;
    private boolean isList = true;//false 为grid布局
    private WebView v4_webview;

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView webView, int i) {
            Log.e("进度", i + "");
            if (i == 100) {
                dismissLoading();
            } else {
                showLoading();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_fanli, null);
        v4_webview = (WebView) view.findViewById(R.id.v4_webview);
        initWebView();
        xRefreshView = (XRefreshView) view.findViewById(R.id.xrefreshview);
        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_test_rv);
        recyclerView.setHasFixedSize(true);
        v4_webview.loadUrl("http://www.50210.com.cn/app/index.php?i=3&c=entry&type=11&do=newcat&m=tiger_newhu");
        initData();
        adapter = new NormalRecyclerAdapter(personList, getActivity());
        // 设置静默加载模式
//        xRefreshView1.setSilenceLoadMore();
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(adapter);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(false);
//        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.enablePullUpWhenLoadCompleted(true);
        //设置静默加载时提前加载的item个数
//        xRefreshView1.setPreLoadCount(4);
        //设置Recyclerview的滑动监听
        xRefreshView.setOnRecyclerViewScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LogUtils.e("onScrollStateChanged");
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LogUtils.e("onScrolled");
            }
        });
        xRefreshView.setXRefreshViewListener(this);
     /*   xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        xRefreshView.stopRefresh();
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
//                        for (int i = 0; i < 6; i++) {
//                            recyclerviewAdapter.insert(new Person("More ", mLoadCount + "21"),
//                                    recyclerviewAdapter.getAdapterItemCount());
//                        }
                        mLoadCount++;
                        if (mLoadCount >= 3) {//模拟没有更多数据的情况
                            xRefreshView.setLoadComplete(true);
                        } else {
                            // 刷新完成必须调用此方法停止加载
                            xRefreshView.stopLoadMore(false);
                            //当数据加载失败 不需要隐藏footerview时，可以调用以下方法，传入false，不传默认为true
                            // 同时在Footerview的onStateFinish(boolean hideFooter)，可以在hideFooter为false时，显示数据加载失败的ui
//                            xRefreshView1.stopLoadMore(false);
                        }
                    }
                }, 1000);
            }
        });*/
//		// 实现Recyclerview的滚动监听，在这里可以自己处理到达底部加载更多的操作，可以不实现onLoadMore方法，更加自由
//		xRefreshView1.setOnRecyclerViewScrollListener(new OnScrollListener() {
//			@Override
//			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//				super.onScrolled(recyclerView, dx, dy);
//				lastVisibleItem = layoutManager.findLastVisibleItemPosition();
//			}
//
//			public void onScrollStateChanged(RecyclerView recyclerView,
//											 int newState) {
//				if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//					isBottom = recyclerviewAdapter.getItemCount() - 1 == lastVisibleItem;
//				}
//			}
//		});
        return view;
    }

    private void initData() {
        for (int i = 0; i < 30; i++) {
            Person person = new Person("name" + i, "" + i);
            personList.add(person);
        }
    }

    public void initWebView() {
        v4_webview.clearCache(true);

//        v4Webview.setWebChromeClient(chromeClient);
        v4_webview.setWebChromeClient(chromeClient);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);

        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");

        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "mingtang_android");
/*        v4_webview.addJavascriptInterface(new ShopDetailActivity.JsInterfaces(this),
                "AndroidWebView");*/
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);

        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);

        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
//        v4Webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");

        v4_webview.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent ev) {

                ((android.webkit.WebView) v).requestDisallowInterceptTouchEvent(true);

                return false;
            }
        });
        v4_webview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {


                return true;
            }


        });
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                xRefreshView.stopRefresh();
            }
        }, 500);
    }

    @Override
    public void onRefresh(boolean isPullDown) {
        xRefreshView.stopRefresh();
        /*  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                xRefreshView.stopRefresh();
            }
        }, 500);*/
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        mLoadCount++;
        if (mLoadCount >= 3) {//模拟没有更多数据的情况
            xRefreshView.setLoadComplete(true);
        } else {
            // 刷新完成必须调用此方法停止加载
            xRefreshView.stopLoadMore(false);
            //当数据加载失败 不需要隐藏footerview时，可以调用以下方法，传入false，不传默认为true
            // 同时在Footerview的onStateFinish(boolean hideFooter)，可以在hideFooter为false时，显示数据加载失败的ui
//                            xRefreshView1.stopLoadMore(false);
        }
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
